package com.infore.metadata.core.utils;

import com.infore.metadata.core.model.SimpleDataSource;
import com.infore.metadata.core.enums.LetterCaseEnum;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库
 *
 * @author ：lijh
 * @date 创建时间： 2022/12/19 11:03
 */
public class JdbcTool {

    /**
     * 通过jdbcUrl获取数据库名
     *
     * @param url
     * @return
     */
    public static String getDbNameByUrl(String url) {
        if (StringTool.isEmpty(url)){
            return null;
        }
        if (url.indexOf('/') > 0) {
            String dbName = url.substring(url.lastIndexOf('/') + 1);
            if (dbName.indexOf('?') > 0) {
                dbName = dbName.substring(0, dbName.indexOf('?'));
            }
            return dbName;
        }
        return null;
    }

    /**
     * 关闭ResultSet
     *
     * @param rs
     */
    public static void closeResultSet(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
    }

    /**
     * 初始化存储数据的时候是否大小写区分
     */
    public static LetterCaseEnum initLetterCase(SimpleDataSource simpleDataSource) {
        try {
            // 获取数据库元数据
            DatabaseMetaData databaseMetaData = simpleDataSource.getConnection().getMetaData();
            // 判断数据库是否不区分大小写
            if (databaseMetaData.storesLowerCaseIdentifiers()) {
                return LetterCaseEnum.LOWER;
            } else if (databaseMetaData.storesUpperCaseIdentifiers()) {
                return LetterCaseEnum.UPPER;
            } else {
                return LetterCaseEnum.NORMAL;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
